<!-- templates/chat.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>在线聊天</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        .chat-container {
            width: 400px;
            margin: 0 auto;
            border: 1px solid #ccc;
            padding: 10px;
            border-radius: 5px;
        }
        .messages {
            height: 300px;
            overflow-y: scroll;
            border-bottom: 1px solid #ccc;
            padding-bottom: 10px;
        }
        .message {
            margin: 5px 0;
        }
        .user-message {
            text-align: right;
        }
        .bot-message {
            text-align: left;
        }
        .input-container {
            display: flex;
            margin-top: 10px;
        }
        .input-container input {
            flex: 1;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        .input-container button {
            padding: 5px 10px;
            border: none;
            background-color: #007bff;
            color: white;
            border-radius: 3px;
            cursor: pointer;
        }
        .input-container button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="messages" id="messages"></div>
        <div class="input-container">
            <input type="text" id="user-input" placeholder="输入消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        function sendMessage() {
            const userInput = document.getElementById('user-input').value;
            if (userInput.trim() === '') return;

            // 显示用户消息
            const messagesContainer = document.getElementById('messages');
            const userMessageDiv = document.createElement('div');
            userMessageDiv.className = 'message user-message';
            userMessageDiv.textContent = `你: ${userInput}`;
            messagesContainer.appendChild(userMessageDiv);

            // 清空输入框
            document.getElementById('user-input').value = '';

            // 发送消息到服务器
            $.ajax({
                url: '/kozi/chat',
                method: 'POST',
                data: { user_message: userInput },
                success: function(response) {
                    // 显示机器人的回复
                    const botMessageDiv = document.createElement('div');
                    botMessageDiv.className = 'message bot-message';
                    botMessageDiv.textContent = `机器人: ${response.bot_response}`;
                    messagesContainer.appendChild(botMessageDiv);
                },
                error: function(error) {
                    console.error('发送消息失败:', error);
                }
            });
        }

    </script>
</body>
</html>
